<?php
require_once 'frontend/application/models/base_model.php';

class User_Model extends Base_Model {
	
	public function save($data) {
		$this->db->insert('users', $data);
		return $this->db->insert_id();
	}
	
	public function save_role($id, $role) {
		$this->db->insert('users_roles', array(
				'user_id' => $id,
				'role' => $role));
		return $this->db->insert_id();
	}
	
	public function activate($id) {
		$this->db
			->where(array('id' => $id))
			->update('users', array('enabled' => true));
		$this->db
			->where(array('user_id' => $id))
			->delete('users_reg_codes');
	}
	
    public function get($id) {
    	return $this->db
	    	->get_where('users', array('id' => $id), 1)
	    	->row_array();
    }
    
    public function get_roles($id) {
    	return $this->db
	    	->select('role')
	    	->where(array('user_id' => $id))
	    	->get('users_roles')->result_array();
    }
    
    public function get_by_email($email) {
    	return $this->db
	    	->get_where('users', array('email' => $email), 1)
	    	->row_array();
    }
    
    public function exist($email) {
    	$result = $this->db
    		->select('id')
    		->where(array('email' => $email))
    		->get('users', 1);
    	
    	return (boolean) $result->num_rows;
    }
    
    public function generate_registration_code($id) {
    	$utils = Application::load_library('utils');
    	$code = $utils->random_string(10);
    	$this->db
    		->insert('users_reg_codes', array('user_id' => $id, 'code' => $code));
    	return $code;
    }
    
    public function get_registration_code($id) {
    	$result = $this->db
    		->select('code')
    		->where(array('user_id' => $id))
    		->get('users_reg_codes')->row_array();
    
    	if (empty($result)) return false;
    
    	return $result['code'];
    }
}